package com.wangsd.common.jwt;

import com.wangsd.common.exception.BusinessErrorEnum;
import com.wangsd.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 拦截器
 * 获取token并验证token
 */
@Slf4j
public class JWTAuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //如果不是映射到方法就直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        log.debug("请求方法==" + method.getName());
        //检查是否有passtoken注释，有则跳过认证
        if(method.isAnnotationPresent(PassToken.class)){
//            PassToken passToken = method.getAnnotation(PassToken.class);
//            if(passToken.required()){
//                return true;
//            }
            return true;
        } else {//默认全部检查
//            if(method.isAnnotationPresent(UserLoginToken.class)){
//                UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
//                if(userLoginToken.required()){
//                }
//            }
            LoginUser loginUser = this.tokenService.getLoginUser(request);
            if(loginUser == null){
                throw new BusinessException(BusinessErrorEnum.USER_NO_PERMISSION, request.getRequestURI() + "||没有权限非法访问");
            }
            tokenService.refreshToken(loginUser);
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
